<template>
    <el-dialog
      v-model="isImageViewerVisible"
      :show-close="true"
      custom-class="image-viewer-dialog"
      @closed="resetImageScale"
      :style="{ width: dialogWidth }"
    >
      <!-- 关闭按钮 -->
      <span class="close-icon el-icon-close" @click="closeImageViewer"></span>
  
      <!-- 图片容器 -->
      <div class="image-container">
        <img
          ref="imageElement"
          :style="imageStyle"
          :src="imageSrc"
          alt="放大图片"
          @wheel.prevent="handleWheel"
        />
      </div>
    </el-dialog>
  </template>
  
  <script setup>
  import { ref, computed, onMounted, onUnmounted  } from 'vue'
  
  // 定义 props 接收外部传入的图片路径
  const props = defineProps({
    imageSrc: {
      type: String,
      default: null
    }
  })
  
  // 控制弹窗显示
  const isImageViewerVisible = ref(false)
  // 对话框宽度
const dialogWidth = ref('')

// 计算对话框宽度为屏幕高度的50%
const calculateDialogWidth = () => {
  const width = `${window.innerHeight * 0.5}px`
  dialogWidth.value = width
}
  // 图片缩放比例
  const scale = ref(1)
  
  // 打开图片查看器
  const openImageViewer = () => {
    isImageViewerVisible.value = true
  }
  
  // 关闭图片查看器
  const closeImageViewer = () => {
    isImageViewerVisible.value = false
  }
  
  // 处理滚轮缩放
  const handleWheel = (event) => {
    if (event.deltaY < 0) {
      scale.value = Math.min(scale.value + 0.1, 5) // 放大，最大到5倍
    } else {
      scale.value = Math.max(scale.value - 0.1, 0.2) // 缩小，最小到原始大小
    }
  }
  
  // 关闭弹窗时重置缩放
  const resetImageScale = () => {
    scale.value = 1
  }
  
  // 动态计算图片样式
  const imageStyle = computed(() => ({
    transform: `scale(${scale.value})`,
    transition: 'transform 0.2s ease',
    transformOrigin: 'center center',
    width: '100%',
  }))

  // 监听窗口大小变化
const onWindowResize = () => {
  calculateDialogWidth()
}

onMounted(() => {
  calculateDialogWidth()
  window.addEventListener('resize', onWindowResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', onWindowResize)
})
  
  // 暴露 openImageViewer 方法给父组件
  defineExpose({
    openImageViewer
  })
  </script>
  
  <style scoped>
  /* 弹窗容器样式 */
  .image-viewer-dialog {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 !important; /* 移除默认的padding */
    position: relative;
  }
  
  /* 关闭按钮 */
  .close-icon {
    position: absolute;
    top: 10px;
    right: 10px;
    font-size: 24px;
    cursor: pointer;
    color: #909399;
    z-index: 10;
  }
  
  .close-icon:hover {
    color: #303133;
  }
  
  /* 图片容器：居中显示图片 */
  .image-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  /* 图片样式 */
  .image-container img {
    max-height: 100%;
    user-select: none;
  }
  </style>